package org.gikolet.ch2.android.widget;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.text.Spannable;

public class ResesManager {

	private Map<Integer, Object> resAnchorTable;

	public ResesManager() {
		this.resAnchorTable = new HashMap<Integer, Object>();
	}

	@SuppressWarnings("unchecked")
	public void add(int resNo, Spannable res) {
		Integer resNoObj = resNo;

		ResAnchorSpan[] spans = res.getSpans(0, res.length(),
				ResAnchorSpan.class);

		for (int i = 0; i < spans.length; i++) {
			int startResNo = spans[i].getStartResNo();
			int endResNo = spans[i].getEndResNo();

			for (; startResNo <= endResNo; startResNo++) {
				Integer startObj = startResNo;

				Object obj = this.resAnchorTable.get(startObj);

				if (obj == null) {
					this.resAnchorTable.put(startObj, resNoObj);

				} else if (obj instanceof List) {
					List<Integer> reses = (List<Integer>) obj;
					reses.add(resNoObj);

				} else {
					List<Integer> reses = new ArrayList<Integer>();

					reses.add(resNoObj);

					this.resAnchorTable.put(startObj, reses);
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	public int[] getResAnchorRef(int resNo) {
		Object obj = this.resAnchorTable.get(resNo);

		int[] resNoArray;

		if (obj == null) {
			resNoArray = new int[0];

		} else if (obj instanceof List) {
			List<Integer> reses = (List<Integer>) obj;

			resNoArray = new int[reses.size()];
			for (int i = 0; i < resNoArray.length; i++) {
				resNoArray[i] = reses.get(i);
			}

		} else {
			resNoArray = new int[] { ((Integer) obj).intValue() };
		}

		return resNoArray;
	}
}
